package control

import (
	"asystem/db"
	"strings"
)

var hostId, id int
var dat *db.CodeBom = &db.CodeBom{}

// bindCodeToCodeBom 绑定条码时存储到数据库操作函数
func bindCodeToCodeBom(hostType int, code string) (err error) {
	// 判断传入的条码是否为主条码
	if hostType == 1 {
		if strings.HasPrefix(code, "WM") {
			hostId, err = db.GetCodeId(code)
			if err != nil {
				return err
			}
			dat = &db.CodeBom{
				BId:   hostId,
				ParId: 0,
			}
			if err = db.InsertCodeIdToCodeBom(dat); err != nil {
				return err
			}
		}
	} else if hostType == 2 {
		if strings.HasPrefix(code, "DP") {
			hostId, err = db.GetCodeId(code)
			if err != nil {
				return err
			}
			dat = &db.CodeBom{
				BId:   hostId,
				ParId: 0,
			}
			if err = db.InsertCodeIdToCodeBom(dat); err != nil {
				return err
			}
		}
	} else {
		if strings.HasPrefix(code, "LB") {
			hostId, err = db.GetCodeId(code)
			if err != nil {
				return err
			}
			dat = &db.CodeBom{
				BId:   hostId,
				ParId: 0,
			}
			if err = db.InsertCodeIdToCodeBom(dat); err != nil {
				return err
			}
		}
	}
	id, err = db.GetCodeId(code)
	if err != nil {
		return err
	}
	dat = &db.CodeBom{
		BId:   id,
		ParId: hostId,
	}
	if err = db.InsertCodeIdToCodeBom(dat); err != nil {
		return err
	}

	return nil
}
